<template>
  <div class="app-container">
    <!-- 操作工具栏 -->
    <div class="control-bar">
      <div class="left">
        <!-- 搜索输入框 -->
        <el-input
          v-model="searchInput"
          placeholder="搜索桌号"
          clearable
          style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <!-- 状态筛选下拉 -->
        <el-select
          v-model="filterStatus"
          placeholder="全部状态"
          clearable
          style="width: 120px; margin-left: 10px"
        >
          <el-option label="待处理" value="0" />
          <el-option label="制作中" value="1" />
          <el-option label="已完成" value="2" />
        </el-select>
      </div>

      <!-- 新建订单按钮 -->
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新建订单
      </el-button>
    </div>

    <!-- 订单表格 -->
    <el-table
      :data="filteredOrders"
      border
      stripe
      style="width: 100%; height: calc(100vh - 160px)"
    >
      <!-- 展开行显示菜品详情 -->
      <el-table-column type="expand" width="60">
        <template #default="{row}">
          <div class="order-details">
            <!-- 菜品列表 -->
            <div class="dish-list">
              <div v-for="(dish, index) in row.dishes" :key="index" class="dish-item">
                <el-image class="dish-image" :src="dish.image" fit="cover" />
                <div class="dish-info">
                  <h4>{{ dish.name }}</h4>
                  <div class="meta">
                    <span class="price">¥{{ dish.price.toFixed(2) }}</span>
                    <span class="quantity">x{{ dish.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单汇总信息 -->
            <div class="order-summary">
              <div class="people">顾客人数：{{ row.people }}人</div>
              <div class="time">下单时间：{{ formatTime(row.createTime) }}</div>
              <div class="total">总计：¥{{ row.total.toFixed(2) }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 表格列定义 -->
      <el-table-column prop="orderNo" label="订单号" min-width="200" align="center" />
      <el-table-column prop="table" label="桌号" min-width="120" align="center" />
      <el-table-column prop="people" label="人数" min-width="100" align="center" />
      <el-table-column label="下单时间" min-width="180" align="center">
        <template #default="{row}">{{ formatTime(row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="状态" min-width="120" align="center">
        <template #default="{row}">
          <el-tag :type="statusStyle[row.status].type" effect="light">
            {{ statusStyle[row.status].text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总金额" min-width="140" align="center">
        <template #default="{row}">
          <span class="total-amount">¥{{ row.total.toFixed(2) }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" min-width="280" align="center" fixed="right">
        <template #default="{row}">
          <el-button
            size="small"
            type="info"
            @click="showOrderDetail(row)"
          >
            <el-icon><View /></el-icon> 查看
          </el-button>
          <el-button
            size="small"
            :type="row.status === 0 ? 'primary' : 'success'"
            @click="changeStatus(row)"
          >
            {{ row.status === 0 ? '开始制作' : '完成订单' }}
          </el-button>
          <el-button type="danger" size="small" @click="cancelOrder(row)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建订单对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建订单" width="800px">
      <el-form :model="newOrder" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 桌号选择 -->
            <el-form-item label="桌号" required>
              <el-select
                v-model="newOrder.table"
                placeholder="请选择桌号"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="table in availableTables"
                  :key="table"
                  :label="`${table}号桌`"
                  :value="table"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 人数选择 -->
            <el-form-item label="顾客人数" required>
              <el-input-number
                v-model="newOrder.people"
                :min="1"
                :max="12"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>菜品选择</el-divider>

        <div class="dish-selector">
          <!-- 菜品搜索 -->
          <el-input
            v-model="dishSearch"
            placeholder="搜索菜品..."
            clearable
            style="width: 300px; margin-bottom: 15px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <!-- 可选菜品网格 -->
          <div class="dish-grid">
            <div
              v-for="dish in filteredDishes"
              :key="dish.id"
              class="dish-card"
              @click="addDish(dish)"
            >
              <el-image class="dish-thumb" :src="dish.image" fit="cover" />
              <div class="dish-info">
                <h4>{{ dish.name }}</h4>
                <p class="price">¥{{ dish.price.toFixed(2) }}</p>
              </div>
            </div>
          </div>

          <el-divider>已选菜品</el-divider>

          <!-- 已选菜品展示 -->
          <div class="selected-dishes">
            <el-tag
              v-for="(item, index) in newOrder.dishes"
              :key="index"
              closable
              @close="removeDish(index)"
              type="info"
            >
              {{ item.name }} x{{ item.quantity }}
            </el-tag>
          </div>
        </div>
      </el-form>

      <!-- 对话框操作按钮 -->
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">提交订单</el-button>
      </template>
    </el-dialog>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="`订单详情 - ${detailDialog.currentOrder?.table}桌`"
      width="800px"
    >
      <el-table :data="detailDialog.currentOrder?.dishes" border>
        <el-table-column prop="name" label="菜品名称" width="180" />
        <el-table-column label="数量" width="80" align="center">
          <template #default="{row}">{{ row.quantity }}</template>
        </el-table-column>
        <el-table-column label="单价" width="120" align="right">
          <template #default="{row}">¥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column label="口味要求">
          <template #default="{row}">{{ row.specs || '无' }}</template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{row}">{{ row.note || '无' }}</template>
        </el-table-column>
        <el-table-column label="小计" width="120" align="right">
          <template #default="{row}">¥{{ (row.price * row.quantity).toFixed(2) }}</template>
        </el-table-column>
      </el-table>

      <div class="order-summary">
        <div class="summary-item">
          <span>桌 号：</span>
          <span class="value">{{ detailDialog.currentOrder?.table }}</span>
        </div>
        <div class="summary-item">
          <span>订单号：</span>
          <span class="value">{{ detailDialog.currentOrder?.orderNo }}</span>
        </div>
        <div class="summary-item total">
          <span>总 计：</span>
          <span class="value">¥{{ detailDialog.currentOrder?.total?.toFixed(2) }}</span>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Search, Plus } from '@element-plus/icons-vue'

// 订单状态样式配置
const statusStyle = {
  0: { text: '待处理', type: 'warning' },
  1: { text: '制作中', type: 'primary' },
  2: { text: '已完成', type: 'success' }
}

// 模拟菜品数据（开发用）
const menu = [
  { id: 1, name: '菲力牛排', price: 228, image: 'https://source.unsplash.com/random/200x200?steak', specs: '五分熟', note: '不要黑椒汁' },
  { id: 2, name: '意大利面', price: 68, image: 'https://source.unsplash.com/random/200x200?pasta' },
  { id: 3, name: '蔬菜沙拉', price: 38, image: 'https://source.unsplash.com/random/200x200?salad', specs: '油醋汁', note: '多加坚果' },
  { id: 4, name: '奶油蘑菇汤', price: 28, image: 'https://source.unsplash.com/random/200x200?soup' }
]

// 模拟订单数据（开发用）
const orders = ref([
  {
    id: 1,
    orderNo: '20231123001',
    table: 'A01',
    people: 4,
    status: 0,
    createTime: '2023-11-23 10:30:45',
    dishes: [
      { ...menu[0], quantity: 1 },
      { ...menu[2], quantity: 2 }
    ],
    total: 228 + (38 * 2)
  },
  {
    id: 2,
    orderNo: '20231123002',
    table: 'B02',
    people: 2,
    status: 1,
    createTime: '2023-11-22 19:15:20',
    dishes: [
      { ...menu[1], quantity: 2 }
    ],
    total: 68 * 2
  }
])

/* 响应式数据管理 */
const searchInput = ref('') // 搜索关键词
const filterStatus = ref('') // 筛选状态
const showCreateDialog = ref(false) // 新建订单对话框显示状态
const dishSearch = ref('') // 菜品搜索关键词
const availableTables = ['A01', 'A02', 'B01', 'B02', 'C01', 'C02'] // 可用桌号列表
const newOrder = reactive({ // 新建订单表单数据
  table: '',
  people: 2,
  dishes: []
})

// 新增响应式数据
const detailDialog = reactive({
  visible: false,
  currentOrder: null
})

/* 计算属性 */
// 过滤后的订单列表
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const matchTable = order.table.toLowerCase().includes(searchInput.value.toLowerCase())
    const matchStatus = filterStatus.value !== '' ? order.status === parseInt(filterStatus.value) : true
    return matchTable && matchStatus
  })
})

// 过滤后的菜品列表
const filteredDishes = computed(() => {
  return menu.filter(dish =>
    dish.name.toLowerCase().includes(dishSearch.value.toLowerCase())
  )
})

/* 方法定义 */
// 时间格式化显示
const formatTime = (timeStr) => {
  return timeStr ? timeStr.slice(0, 16).replace(' ', ' ') : '--'
}

// 打开新建订单对话框
const openCreateDialog = () => {
  showCreateDialog.value = true
  newOrder.dishes = []
}

// 添加菜品到订单
const addDish = (dish) => {
  const existing = newOrder.dishes.find(d => d.id === dish.id)
  if (existing) {
    existing.quantity++
  } else {
    newOrder.dishes.push({ ...dish, quantity: 1 })
  }
}

// 移除已选菜品
const removeDish = (index) => {
  newOrder.dishes.splice(index, 1)
}

// 提交新订单
const submitOrder = () => {
  if (!newOrder.table || newOrder.dishes.length === 0) {
    ElMessage.error('请填写完整信息')
    return
  }

  orders.value.unshift({
    id: Date.now(),
    orderNo: `2023${Date.now().toString().slice(-6)}`, // 简单生成订单号
    ...newOrder,
    status: 0,
    createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    total: newOrder.dishes.reduce((sum, dish) => sum + (dish.price * dish.quantity), 0)
  })

  showCreateDialog.value = false
  ElMessage.success('订单创建成功')
  Object.assign(newOrder, {
    table: '',
    people: 2,
    dishes: []
  })
}

// 显示订单详情
const showOrderDetail = (order) => {
  detailDialog.currentOrder = order
  detailDialog.visible = true
}

// 更改订单状态
const changeStatus = (order) => {
  if (order.status === 0) {
    order.status = 1
    ElMessage.success('已开始制作')
  } else if (order.status === 1) {
    order.status = 2
    setTimeout(() => {
      orders.value = orders.value.filter(o => o.id !== order.id)
    }, 1000)
    ElMessage.success('订单已完成')
  }
}

// 取消订单
const cancelOrder = (order) => {
  ElMessageBox.confirm(`确定取消 ${order.table} 桌订单？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(o => o.id !== order.id)
    ElMessage.success('订单已取消')
  })
}
</script>

<style scoped>
/* 主容器样式 */
.app-container {
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
  background: #f5f7fa;
}

/* 控制工具栏样式 */
.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

/* 订单详情样式 */
.order-details {
  padding: 15px;
  background: #f8f9fa;
}

.dish-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
}

.dish-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
}

.meta {
  display: flex;
  justify-content: space-between;
  color: #666;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

/* 菜品选择器样式 */
.dish-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.dish-card {
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: transform 0.2s;
  background: #fff;

  &:hover {
    transform: translateY(-3px);
  }
}

.dish-thumb {
  width: 100%;
  height: 120px;
}

.selected-dishes .el-tag {
  margin: 5px;
}

.total-amount {
  color: #f56c6c;
  font-weight: 600;
}

/* 新增订单详情样式 */
.order-summary {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  font-size: 14px;
}

.summary-item.total {
  border-top: 1px solid #eee;
  padding-top: 12px;
  margin-top: 12px;
  font-size: 16px;
  font-weight: 600;
}

.summary-item .value {
  color: #606266;
  font-weight: 500;
}

.summary-item.total .value {
  color: #f56c6c;
}

/* 调整操作按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-border-color: #ebeef5;

  th.el-table__cell {
    background: #f8f9fa;
  }

  .el-table__body-wrapper {
    overflow-x: auto;
  }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .control-bar {
    flex-direction: column;
    gap: 10px;

    .left {
      width: 100%;
    }

    .el-button {
      width: 100%;
    }
  }
}
</style>
